package tree;

/**
 * Created with IntelliJ IDEA.
 * Description: 701. 二叉搜索树中的插入操作
 * User: Li_yizYa
 * Date: 2025/6/10
 * Time: 19:56
 */
public class Solution33 {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        TreeNode cur = root;
        TreeNode pre = null;
        while (cur != null) {
            if (cur.val > val) {
                if (cur.left == null) {
                    break;
                }
                cur = cur.left;
            } else if (cur.val < val) {
                if (cur.right == null) {
                    break;
                }
                cur = cur.right;
            }

        }
        if (cur.val < val) {
            cur.right = new TreeNode(val);
        } else {
            cur.left = new TreeNode(val);
        }
        return root;
    }
}
